﻿from selenium import webdriver  # 用来驱动浏览器的
from selenium.webdriver import ActionChains  # 破解滑动验证码的时候用的 可以拖动图片
from selenium.webdriver.common.by import By  # 按照什么方式查找，By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys  # 键盘按键操作
from selenium.webdriver.support import expected_conditions as EC  # 和下面WebDriverWait一起用的
from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
import pycurl
#python main.py --url https://weibo.com/p/1003061765979160/photos?from=page_100306#wbphoto_nav --path g:/download3 --times=30
import time
import argparse
import os
import wget
import certifi
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--url',type=str,nargs='+')
    parser.add_argument('--path',type=str,nargs='+')
    parser.add_argument('--times',type=int,nargs='+')
    args = parser.parse_args()
    print(args)
    targeturl =args.url[0]
    targetpath =args.path[0]
    times =args.times[0]
    options = webdriver.ChromeOptions()
    profile_dir=r"C:\\Users\\wuyj\AppData\\Local\\Google\\Chrome\\User Data"
    options.binary_location = "C:\\Users\\wuyj\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"

    prefs = {'profile.default_content_settings.popups': 0,
         'download.default_directory': targetpath}
    options.add_argument("user-data-dir="+os.path.abspath(profile_dir)) 
    options.add_experimental_option('prefs', prefs)
    options.add_argument('--disable-gpu')
    options.add_argument('--ignore-certificate-errors')
    browser = webdriver.Chrome(chrome_options=options)
    browser.implicitly_wait(6) 

    browser.get(targeturl)
    time.sleep(3)
# 下拉滚动条, 循环多次下拉, 可以获取到更多的图片
    for i in range(times):
        browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
        time.sleep(1)
     
    try:
        imgurls=[]
        imgs=browser.find_elements_by_xpath("//img[@class='photo_pict']")
        for img in imgs :
            imgurl=img.get_attribute('src')
            if imgurl:
                imgurl=imgurl.replace("/thumb300/","/mw1024/")
                imgurls.append(imgurl)
                print(imgurl)
        for imgurl in imgurls:
            file_name =wget.filename_from_url(imgurl)   
            returned_value  =os.system("curl -k -o "+os.path.join(targetpath, file_name)+" "+imgurl) 
            print('returned value:', returned_value)   
    except Exception as e:
        print("error:"+str(e))
    browser.quit()